package com.sy.pet.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sy.pet.commom.enmu.ResponseCode;
import com.sy.pet.config.excetion.ServiceExcetion;
import com.sy.pet.dto.PageDTO;
import com.sy.pet.dto.PetTagDTO;
import com.sy.pet.entity.PetTag;
import com.sy.pet.mapper.PetTagMapper;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @Author: liangSY
 * @Date: 2024/9/14
 * @ClassName: PetTagService
 * @Description: PetTagService描述
 */
@Service
public class PetTagService extends ServiceImpl<PetTagMapper, PetTag> {

    public void add(PetTagDTO dto){
        LambdaQueryWrapper<PetTag> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PetTag::getTitle, dto.getName());
        queryWrapper.eq(PetTag::getActive, true);
        PetTag petTag = baseMapper.selectOne(queryWrapper);
        if(!Objects.isNull(petTag)){
            throw new ServiceExcetion(ResponseCode.DATA_DUPLICATION.getCode(),ResponseCode.DATA_DUPLICATION.getMessage());
        }
        baseMapper.insert(PetTag.builder().title(dto.getName()).active(true).createTime(LocalDateTime.now()).build());
    }

    public void edit(PetTagDTO dto){
        PetTag petTag = baseMapper.selectById(dto.getId());
        if(Objects.isNull(petTag)){
            throw new ServiceExcetion(ResponseCode.DATA_NOT_FOUND);
        }
        petTag.setTitle(dto.getName());
        baseMapper.updateById(petTag);
    }

    public void remove(String id){
        PetTag petTag = baseMapper.selectById(id);
        if(Objects.isNull(petTag)){
            throw new ServiceExcetion(ResponseCode.DATA_NOT_FOUND);
        }
        petTag.setActive(false);
        baseMapper.updateById(petTag);
    }

    public IPage<PetTag> getByPage(PageDTO dto){
        LambdaQueryWrapper<PetTag> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PetTag::getActive, true);
        Page<PetTag> page = new Page(dto.getPage(), dto.getSize());
       return baseMapper.selectPage(page,queryWrapper);
    }

    public List<PetTag> getAll(){
        LambdaQueryWrapper<PetTag> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PetTag::getActive, true);
        return baseMapper.selectList(queryWrapper);
    }
}
